#ifndef _GLWINDOW_H
#define _GLWINDOW_H

#include <cassert>
#include <cstdlib>
#include <vector>

#include <gtkmm.h>
#include <gtkglmm.h>

#include "renderer.h"
#include "reseatable_reference.h"

class GLWindowContext
{
	public:
		GLWindowContext(Glib::RefPtr<Gdk::GL::Window> windowref, Glib::RefPtr<Gdk::GL::Context> contextref) : valid(false)
		{
			glwindow = windowref;
			if (glwindow->gl_begin(contextref))
				valid = true;
		}
		
		~GLWindowContext()
		{
			glwindow->gl_end();
		}
		
		operator bool() const {return valid;}
		
		Glib::RefPtr<Gdk::GL::Window> glwindow;
		
	private:
		bool valid;
};

class GLWindow : public Gtk::DrawingArea,
	public Gtk::GL::Widget<GLWindow>
{
	public:
		GLWindow();
		
		virtual ~GLWindow()
		{
			
		}
		
		const std::string & getError() const {return error;}
		double getFps() const {return fpsFiltered;}
		Renderer & getRenderer() {return renderer;}
		void sendSceneToRenderer(const SceneNode & root, bool fast = false);
		
		sigc::signal <void, std::string> outputWindow;
		
	protected:
		
		virtual void on_realize();
		virtual bool on_configure_event(GdkEventConfigure* event);
		virtual bool on_expose_event(GdkEventExpose* event);
		virtual bool on_map_event(GdkEventAny* event);
		virtual bool on_unmap_event(GdkEventAny* event);
		virtual bool on_visibility_notify_event(GdkEventVisibility* event);
		virtual bool on_idle();
		
	private:
		Renderer renderer;
		
		std::string error;
		
		double fpsFiltered;
		Glib::Timer fpsTimer;
		
		sigc::connection connectionIdle;
		
		reseatable_reference <const SceneNode> sceneRoot;
		
		void writeOutput(std::string text);
		void writeGlLog(std::string text);
		void setupViewport();
		
		void reconnectIdle();
};

#endif
